package com.zlzlib.libindex.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;


import com.zlzlib.libindex.R;
import com.zlzlib.libindex.bean.BaseIndexBean;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by zlz on 2019/11/1.
 * 配合RecyclerView 的侧索引栏
 */
public abstract class BaseIndexBar extends View {

    //索引数据源
    protected List<String> mIndexData = new ArrayList<>();
    //是否需要根据实际的数据来生成索引数据源（例如 只有 A B C 三种tag，那么索引栏就 A B C 三项）
    protected boolean isNeedRealIndex = false;

    //View的宽高
    private int mWidth, mHeight;
    //每个index区域的高度
    private int mGapHeight;
    //文字大小  高度
    private float mTextSize, mTextH;

    private Paint mPaint;

    //手指按下时的背景色
    private int mPressedBackground;

    //旁边字母的颜色
    private int text_bg = Color.parseColor("#259afa");

    //用于特写显示正在被触摸的index值
    private TextView mPressedShowView;

    //RecyclerView 头部view个数
    private int mHeaderCount = 0;

    private LinearLayoutManager mLayoutManager;

    private IndexPressedListener pressedListener;


    //默认的索引
    protected abstract String[] defDataString();

    protected abstract List<? extends BaseIndexBean> sourceData();

    public BaseIndexBar(Context context) {
        super(context);
        init(context, null, 0);
    }

    public BaseIndexBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public BaseIndexBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        mTextSize = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics());//默认的TextSize
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.IndexBar, defStyleAttr, 0);
        int n = typedArray.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = typedArray.getIndex(i);
            if (attr == R.styleable.IndexBar_indexBarTextSize) {
                mTextSize = typedArray.getDimensionPixelSize(attr, (int) mTextSize);
            } else if (attr == R.styleable.IndexBar_indexBarPressBackground) {
                mPressedBackground = typedArray.getColor(attr, Color.BLACK);
            } else if (attr == R.styleable.IndexBar_indexBarTextColor) {
                text_bg = typedArray.getColor(attr, Color.parseColor("#259afa"));
            }
        }
        typedArray.recycle();
        initIndexData();
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(text_bg);
        mTextH = mPaint.descent() - mPaint.ascent();
        initListener();
    }

    //初始化索引
    protected void initIndexData() {
        if (isNeedRealIndex) {
            mIndexData = new ArrayList<>();
        } else {
            mIndexData = Arrays.asList(defDataString());
        }
    }

    private void initListener() {
        setPressedListener(new IndexPressedListener() {
            @Override
            public void onIndexPressed(int index, String text) {
                if (mPressedShowView != null) {
                    //显示hintTexView
                    mPressedShowView.setVisibility(View.VISIBLE);
                    mPressedShowView.setText(text);
                }
                //滑动 RecyclerView
                if (mLayoutManager != null) {
                    int position = getPosByTag(text);
                    if (position != -1) {
                        mLayoutManager.scrollToPositionWithOffset(position, 0);
                    }
                }
            }

            @Override
            public void onMotionEventEnd() {
                if (mPressedShowView != null) {
                    //隐藏hintTextView
                    mPressedShowView.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //取出宽高的MeasureSpec  Mode 和Size
        int wMode = MeasureSpec.getMode(widthMeasureSpec);
        int wSize = MeasureSpec.getSize(widthMeasureSpec);
        int hMode = MeasureSpec.getMode(heightMeasureSpec);
        int hSize = MeasureSpec.getSize(heightMeasureSpec);
        int measureWidth = 0, measureHeight = (int) mTextH;//最终测量出来的宽高
        //得到合适宽度：
        String index;//每个要绘制的index内容
        for (int i = 0; i < mIndexData.size(); i++) {
            index = mIndexData.get(i);
            measureWidth = (int) Math.max(mPaint.measureText(index), measureWidth);//循环结束后，得到index的最大宽度
        }
        measureHeight *= mIndexData.size();
        switch (wMode) {
            case MeasureSpec.EXACTLY:
                measureWidth = wSize;
                break;
            case MeasureSpec.AT_MOST:
                measureWidth = Math.min(measureWidth, wSize);//wSize此时是父控件能给子View分配的最大空间
                break;
            case MeasureSpec.UNSPECIFIED:
                break;
        }
        switch (hMode) {
            case MeasureSpec.EXACTLY:
                measureHeight = hSize;
                break;
            case MeasureSpec.AT_MOST:
                measureHeight = Math.min(measureHeight, hSize);//hSize此时是父控件能给子View分配的最大空间
                break;
            case MeasureSpec.UNSPECIFIED:
                break;
        }
        setMeasuredDimension(measureWidth, measureHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int t = getPaddingTop();//top的基准点(支持padding)
        String index;//每个要绘制的index内容
        for (int i = 0; i < mIndexData.size(); i++) {
            index = mIndexData.get(i);
            //获得画笔的FontMetrics，用来计算baseLine。因为drawText的y坐标，代表的是绘制的文字的baseLine的位置
            Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
            //计算出在每格index区域，竖直居中的baseLine值
            int baseline = (int) ((mGapHeight - fontMetrics.bottom - fontMetrics.top) / 2);
            //调用drawText，居中显示绘制index
            canvas.drawText(index, mWidth / 2 - mPaint.measureText(index) / 2, t + mGapHeight * i + baseline, mPaint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                setBackgroundColor(mPressedBackground);//手指按下时背景变色
                //注意这里没有break，因为down时，也要计算落点 回调监听器
            case MotionEvent.ACTION_MOVE:
                float y = event.getY();
                //通过计算判断落点在哪个区域：
                int pressI = (int) ((y - getPaddingTop()) / mGapHeight);
                //边界处理（在手指move时，有可能已经移出边界，防止越界）
                if (pressI < 0) {
                    pressI = 0;
                } else if (pressI >= mIndexData.size()) {
                    pressI = mIndexData.size() - 1;
                }
                //回调监听器
                if (null != pressedListener && pressI > -1 && pressI < mIndexData.size()) {
                    pressedListener.onIndexPressed(pressI, mIndexData.get(pressI));
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
            default:
                setBackgroundResource(android.R.color.transparent);//手指抬起时背景恢复透明
                //回调监听器
                if (null != pressedListener) {
                    pressedListener.onMotionEventEnd();
                }
                break;
        }
        return true;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
        computeGapHeight();
    }

    /**
     * 以下情况调用：
     * 1 在数据源改变
     * 2 控件size改变时
     * 计算gapHeight  判断此时文字大小是否超出最大容量  并适当减小
     */
    protected void computeGapHeight() {
        if (mIndexData.isEmpty()) {
            return;
        }
        mGapHeight = (mHeight - getPaddingTop() - getPaddingBottom()) / mIndexData.size();
        if (mGapHeight >= mTextH) {
            mPaint.setTextSize(mTextSize);
        } else {
            mPaint.setTextSize(mTextSize * mGapHeight / mTextH);
        }
    }

    public void setPressedShowView(TextView mPressedShowView) {
        this.mPressedShowView = mPressedShowView;
    }

    public void setNeedRealIndex(boolean needRealIndex) {
        isNeedRealIndex = needRealIndex;
        initIndexData();
    }

    public void setPressedListener(IndexPressedListener pressedListener) {
        this.pressedListener = pressedListener;
    }

    public int getHeaderCount() {
        return mHeaderCount;
    }

    public void setHeaderCount(int mHeaderCount) {
        this.mHeaderCount = mHeaderCount;
    }

    public void setLayoutManager(LinearLayoutManager mLayoutManager) {
        this.mLayoutManager = mLayoutManager;
    }

    /**
     * 当前被按下的index的监听器
     */
    public interface IndexPressedListener {

        void onIndexPressed(int index, String text);//当某个Index被按下

        void onMotionEventEnd();//当触摸事件结束
    }

    /**
     * 根据传入的 tag 返回 Pos
     *
     * @param tag
     * @return
     */
    private int getPosByTag(String tag) {
        if (null == sourceData() || sourceData().isEmpty()) {
            return -1;
        }
        if (TextUtils.isEmpty(tag)) {
            return -1;
        }
        for (int i = 0; i < sourceData().size(); i++) {
            if (tag.equals(sourceData().get(i).getTitle())) {
                return i + getHeaderCount();
            }
        }
        return -1;
    }
}
